<template>
  <div>
    <el-dropdown @command="handleCommand" placement="bottom-end">
      <div class="user-info">
        <el-avatar :size="32" class="user-avatar" :src="userStore.avatar">
          {{ userStore.name ? userStore.name.charAt(0) : 'U' }}
        </el-avatar>
        <span class="user-name">{{ userStore.name || '用户' }}</span>
        <el-icon class="dropdown-icon"><ArrowDown /></el-icon>
      </div>
      <template #dropdown>
        <el-dropdown-menu>
          <el-dropdown-item command="profile">
            <el-icon><User /></el-icon>
            个人中心
          </el-dropdown-item>
          <el-dropdown-item command="settings">
            <el-icon><Setting /></el-icon>
            账户设置
          </el-dropdown-item>
          <el-dropdown-item divided command="logout">
            <el-icon><SwitchButton /></el-icon>
            退出登录
          </el-dropdown-item>
        </el-dropdown-menu>
      </template>
    </el-dropdown>

    <!-- 个人信息弹窗 -->
    <ProfileDialog v-model="showProfileDialog" />
  </div>
</template>

<script setup>
import { ref } from 'vue'
import { useRouter } from 'vue-router'
import useUserStore from '@/store/modules/user'
import ProfileDialog from './ProfileDialog.vue'
import { ArrowDown, User, Setting, SwitchButton } from '@element-plus/icons-vue'

const router = useRouter()
const userStore = useUserStore()

// 个人信息弹窗显示状态
const showProfileDialog = ref(false)

const handleCommand = (command) => {
  switch (command) {
    case 'profile':
      // 显示个人信息弹窗
      showProfileDialog.value = true
      break
    case 'settings':
      // 显示个人信息弹窗（账户设置和个人中心合并）
      showProfileDialog.value = true
      break
    case 'logout':
      // 退出登录
      handleLogout()
      break
  }
}

const handleLogout = async () => {
  try {
    await userStore.logOut()
    // 清除登录状态，但保持在dashboard页面
    // 不需要跳转，因为dashboard页面会根据登录状态显示登录弹窗
  } catch (error) {
    console.error('退出登录失败:', error)
  }
}
</script>

<style lang="scss" scoped>
.user-info {
  display: flex;
  align-items: center;
  gap: 8px;
  cursor: pointer;
  padding: 8px 12px;
  border-radius: 6px;
  transition: background-color 0.3s;

  &:hover {
    background-color: #f5f7fa;
  }

  .user-avatar {
    background-color: #409eff;
    color: white;
    font-weight: bold;
  }

  .user-name {
    font-size: 14px;
    color: #333;
    font-weight: 500;
  }

  .dropdown-icon {
    font-size: 12px;
    color: #666;
    transition: transform 0.3s;
  }
}

:deep(.el-dropdown-menu__item) {
  display: flex;
  align-items: center;
  gap: 8px;
  
  .el-icon {
    font-size: 16px;
  }
}
</style>
